<?php
/*****************
*作者：jeff.liu
*联系方式：13810908686
*电子邮件：ljf1279@yeah.net
******************/
class Template extends Object
{
	function __construct($arr = NULL)
	{
		parent::__construct($arr);
//		if($this->DTName == '' && $this->TID > 0)
			$this->DTName = "Table_".$this->TID;
		if(!$this->UrlRule)
			$this->UrlRule = '/${TID}/${YYYY}/${MM}${DD}/${HH}${II}${SS}${D_ID}.html';
	}
	
	
	/******2010.05.05预览功能修改***************/
	function children()
	{
		global $db;
		$arr = NULL;
		$sql = "select * from Template where PID={$this->TID}";
		$result = $db->query($sql);
		while($row = $db->fetch_array($result))
		{
			$arr[] = new Template($row);
		}
		return $arr;
	}
	/******end***************/
	
	//获取表中所有自定义字段
	function Fields($order = "FID")
	{
		global $db;
		$arrReturn = NULL;
		if($order!="")
			$order = "order by $order";
		$sql = "select * from `Field` where TID = '{$this->TID}' $order";
		$result = $db->query($sql);
		while($row = $db->fetch_array($result, MYSQL_ASSOC))
		{
			$arrReturn[] = new Field($row);
		}
		return $arrReturn;
	}
	//拼接建表字符串
	function getCreateTable()
	{
		$fields = $this->Fields();
		$strReturn = "create table `$this->DTName`(`D_ID` int(11) not NULL auto_increment, `url` varchar (255) not NULL ,
					`CreatorID` int(11) not NULL  ,`MenderID` int(11) not NULL ,`CreateTime` int(11) default '0',`MendTime` int (11) default '0',
					 `page_num` int(10) default 1 ";
	
		$strKey = " ,primary key (`D_ID`),key `url` (`url`), key `CreateTime` (`CreateTime`), key `MendTime` (`MendTime`), key `page_num` (`page_num`)";
		if($fields)
		{
			foreach($fields as $field)
			{
				if($field->Depositing == 'Y')
				{
					$Length = "";
					$Default = "";
					if($field->length)
					{
						$Length = " ($field->length) ";
					}
					else
					{
						if(strtolower($field->TFType) == 'varchar')
						{
							$Length = " (200) ";
						}
						if(strtolower($field->TFType) == 'int')
						{
							$Length = " (11) ";
						}
						if(strtolower($field->TFType) == 'double')
						{
							$Length = " (20) ";
						}
					}
					
					if ($field->DefaultVal) {
						$Default = "default '{$field->DefaultVal}'";
					} else {
						$Default = " default '' ";
					}
					if(($field->FIndex == 'INDEX' || $field->FIndex == 'UNIQUE') && !eregi('text',$field->TFType))
					{
						$strKey .= " ,{$field->FIndex} key `{$field->TFName}` (`{$field->TFName}`)";
					}
					$strReturn .= " ,{$field->TFName} {$field->TFType}$Length NOT NULL  $Default";
				}
			}
		}
		$strReturn .= $strKey;
		$strReturn .= ") ENGINE=MyISAM";

		return $strReturn;
	}

	//
	function CreateTable()
	{
		//判断有无重名

		//执行建表操作

		global $db;
		$db->query($this->getCreateTable());
		$db->query("update Template set DTName=concat('Table_',TID) where TID='{$this->TID}'");
		
				/*****************以下代码用于新模板*********/
		//以下代码用于创建数据存取表字段 以及 创建模板页面的js控制，并且入库模板表。
		include("new_template_fields_array.php");//此文件定义模板名称与需要创建数据存取表的字段相对应，定义创建那些字段。
		//$fieldToArray是模板中 的数据存取表与字段对应数组
        if(!empty($templateToFieldArray[$this->TypeName]))
        {
     		include("new_template_jsfunction_arry.php");//定义模板与调用js函数对应数组
			foreach ($templateToFieldArray[$this->TypeName]  AS $key => $values)
			{
				$values['TID'] = $this->TID;
				$Field = new Field($values);
				$req = $Field->add();//增加数据存取表字段
				
			}
			if(!empty($templateToJsfunctionArray[$this->TypeName]))// 往模板中增加js判断处理
			{
				$strJs = 'jQuery(function($){
				';
				foreach ($templateToJsfunctionArray[$this->TypeName]  AS $key => $values)
				{
					$strJs .= ($values);
				}
				$strJs .='});';
				
				$strStyle = '<?php $arr = array("web_type" => "iskysoft"); ?>';
				
				$db->query("update Template set Script='".addslashes($strJs)."' , Style = '".addslashes($strStyle)."'  WHERE TID='{$this->TID}'");
			}
        }
        /*****************以上代码用于新模板*********/
	}

	//
	function getStyle()
	{
		//遍历Style中的宏

		//取得宏算法并替换宏，生成template字串

		//未使用
	}

	//生成模板文件
	function createTemplate()
	{
		//未使用
	}

	//创建文档列表页
	function createListDoc()
	{
		//模板文档数据库字符串
		$idStr = "";
		$fieldStr = "";
		$nameStr  = "";
		//表单字符串
		if($this->Fields("EditOrder,FID")) {
			foreach($this->Fields("EditOrder,FID") as $field)
			{
				if($field->FPropty != "" && $field->Depositing == 'Y')
				{
					$idStr .= "{$field->FID},";
					$fieldStr .= "'{$field->TFName}',";
					$nameStr .= "'{$field->FName}',";
				}
			}
		}
		$idStr = ereg_replace(",$","",$idStr);
		//文档相关信息
		$docConf .= "
\$idStr = array($idStr);
\$fieldStr = array($fieldStr);
\$nameStr = array($nameStr);
\$DTName = '{$this->DTName}';
\$TID = {$this->TID};
\$Template=new Template();
\$Template->getObjById($this->TID,'TID','Template');";
		//加载文档模板
		$file = file_get_contents(TPL_ROOT."/docList.tpl.php");
		//替换一些非静态参数
		$file = ereg_replace("{DOC_CREATE}",$this->createDoc(),$file);
		$file = ereg_replace("{DOC_CONF}",$docConf,$file);
		$file = ereg_replace("{VAR_FORM}",$formStr,$file);
		$file = ereg_replace("{SQL_INSERT}",$sql_insert,$file);
		$file = ereg_replace("{SQL_UPDATE}",$sql_update,$file);
		//生成/更新文件

		$cache = new Cache(array("Content"=>$file,"FilePathName"=>BIN_ROOT."/docList_".$this->TID.".php"));
		$cache->update(true);	
	}
	//创建添加文档程序
	function createAddDoc()
	{
		//BIN_ROOT
		//DOC_ROOT

		//模板文档数据库字符串
		$sqlStr = "";
		//表单字符串
		$formStr = "<form method=\"post\" onsubmit=\"this.sub.disabled='disabled';return checkUrl(this);\">
				<input type=\"hidden\" value=\"true\" name=\"doPost\">
				<input type=\"hidden\" value=\"".$this->TID."\" name=\"TID\">
				<input type=\"hidden\" value=\"<?php echo \$Doc->url; ?>\" name=\"old_url\" id=\"old_url\">
				<input type=\"hidden\" value=\"<?php echo \$_GET['site_id']; ?>\" name=\"site_id\" id=\"site_id\">
				<input type=\"hidden\" value=\"<?php echo \$D_ID;?>\" name=\"D_ID\">
				<input type=\"hidden\" value=\"<?php echo \$currAdmin->AName;?>\" name=\"AName\">
				<table width=\"90%\" cellpadding=\"1\" cellspacing=\"1\" class=\"list-div\">
				<tr>
					<th colspan=\"3\" align=\"left\" style=\"padding:0 0 0 10px;\"> 新建/修改文档 <input type='button' value='返回' onclick='history.go(-1)' /></th>   
				</tr>
				<tr>
					<td width=\"100\">项目</td>
					<td>值</td>
				</tr>";
		$docConf = "";
		
		//表单字符串
		if($this->Fields("EditOrder,FID")) {
		
			foreach($this->Fields("EditOrder,FID") as $field)
			{
				if($field->Depositing == "Y")
					$sqlStr .= " `{$field->TFName}`='\$Doc->{$field->TFName}',";
				$docConf .= "\$Doc->{$field->TFName} = \"".addslashes($field->DefaultVal)."\";\n";
				if(eregi("^form::",$field->FType))
					$formStr .= "<tr>
						<td>".$field->FName."</td>
						<td>".$field->getInput()."</td>
					</tr>";
			}
		}
		$sqlStr .= " `url`='\$Doc->url',";
		$formStr .= "<tr>
				<td>URL</td>
				<td><input type=\"text\" id=\"url\" name=\"url\" value=\"<?php echo \$Doc->url; ?>\" size=\"80\"></td>
			</tr>";
		$formStr .= "<tr>
				<td></td>
				<td><input type=\"submit\" name=\"sub\" value=\"提交\"></td>
			</tr>
		</table>
		</form>";
$formStr .= '<script type="text/javascript">
//note 判断url中是否含有中文字符
function checkUrl( obj ){
	var url = document.getElementById("url").value;
	if( url.search(/[^\x00-\xff]/) != -1 ){
		alert("URL中含有中文字符！");
		obj.sub.disabled="";
		return false;
	}
	if( url.search(/[^\S]/) != -1 ){
		alert("URL中含有空格！");
		obj.sub.disabled="";
		return false;
	}
	var regex = /^(?=.*?[A-Z]).*$/;
	if (regex.test(url))    
	{   
	  alert("URL地址中含有大写字母！");
	  obj.sub.disabled="";
	  return false;   
	}  
}
//note 解析url，取得field_id和key_id
$(function(){
	var url = document.location.href;
	if( url.indexOf("?") != -1 ){
		var query = url.split("?")[1];
		arg = query.split("&");
		for(var i in arg){
			if( arg[i].split("=")[0] == "field_id" ) var field_id = arg[i].split("=")[1];
			if( arg[i].split("=")[0] == "key_id" ) var key_id = arg[i].split("=")[1];
		}
		$("#FORM_FIELD_"+field_id).val(key_id);
		$("#FORM_FIELD_"+field_id).blur();
	}
})
</script>';

		//入库操作字符串
		//$sql_insert = "insert into `{$this->DTName}` set $sqlStr CreateTime='\".time().\"', CreatorID='\".\$_SESSION['AID'].\"', page_num = '{\$Doc->page_num}'";//CreatorID='',
		//note 将CreateTime='\".time().\"', CreatorID='\".\$_SESSION['AID'].\"'去掉，在发布时讲更新为发布时间和发布人id,而不为添加时的时间和Id,用于标记文章是否发布
		$sql_insert = "insert into `{$this->DTName}` set $sqlStr page_num = '{\$Doc->page_num}'";//CreatorID='',
		//更新操作字符串
		$sql_update = "update `{$this->DTName}` set $sqlStr MendTime='\".time().\"',MenderID='\".\$_SESSION['AID'].\"' where D_ID='{\$Doc->D_ID}'";
		//文档相关信息
		$docConf .= "\$DTName = '{$this->DTName}';
\$TID = {$this->TID};
\$Template=new Template();
\$Template->getObjById($this->TID,'TID','Template');";
		//加载文档模板
		$file = file_get_contents(TPL_ROOT."/doc.tpl.php");
		//替换一些非静态参数
		$file = ereg_replace("{DOC_CREATE}",$this->createDoc(),$file);
		$file = ereg_replace("{DOC_CONF}",$docConf,$file);
		$file = ereg_replace("{VAR_FORM}",$formStr,$file);
		$file = ereg_replace("{SQL_INSERT}",$sql_insert,$file);
		$file = ereg_replace("{SQL_UPDATE}",$sql_update,$file);
		//生成/更新文件
		$cache = new Cache(array("Content"=>$file,"FilePathName"=>BIN_ROOT."/doc_".$this->TID.".php"));
		//echo $cache->FilePathName;
		$cache->update(true);
		$this->createListDoc();
	}

	//
	function createDoc()
	{
		$fields = $this->Fields("ExecOrder,FID");
		if(!empty($fields)) {
			foreach($fields as $field)
			{
				if($field->Enable == 'Y')
				{
					if(ereg("^Application",$field->FType))
					{
						$strReturn .= "\$Field_{$field->TFName} = new Field();";
						$strReturn .= "\$Field_{$field->TFName}->getObjById({$field->FID},\"FID\",\"Field\");";
						$strReturn .= "\$F_{$field->TFName} = \$Field_{$field->TFName}->getFunction();";
						$strReturn .= "\$Doc->{$field->TFName} = eval(\$F_{$field->TFName});\n";
					}
					if($field->FType == "Form::Image")
					{
						$strReturn .= "if(!eregi(\"^http:\",\$Doc->{$field->TFName}))\n";
						$strReturn .= "\$Doc->{{$field->FName}} = IMG_URL.\"/\".\$Doc->{$field->TFName};\n";
						
						$strReturn .= "else \$Doc->{{$field->FName}} = \$Doc->{$field->TFName};\n";
					}
					else
					{
						$strReturn .= "\$Doc->{{$field->FName}} = \$Doc->{$field->TFName};\n";
					}
				}
			}
		}
		return $strReturn;
	}

	function add()
	{
		global $db;
		if($this->TName == "")
			return false;
			$UID = intval($_SESSION["AID"]);
//		$UID = $_SESSION['UID'];
//		if(!$UID)
//			return false;
		$sql = "insert into Template set TName = '{$this->TName}', `UrlRule`='{$this->UrlRule}', DTName='{$this->DTName}', `Style`='{$this->Style}', 
		`Config`='{$this->Config}', `Script`='{$this->Script}', CreateTime = '".time()."', PID='{$this->PID}' ,TType = '{$this->TType}',
		TypeName = '{$this->TypeName}', UID = '$UID', web_type = '{$this->web_type}'";
		if($db->query($sql))
		{
			$this->TID = $db->insert_id();
			$this->__construct($this);
			$this->CreateTable();
			return true;
		}
		return false;
	}

	function update($type = '')
	{
		global $db;
		
		if($this->TName == "") {
			return false;
		}
	
		$sql = "update Template set TName = '{$this->TName}', `UrlRule`='{$this->UrlRule}', DTName='{$this->DTName}', `Style`='{$this->Style}',
		 `Config`='{$this->Config}', `Script`='{$this->Script}', PID='{$this->PID}',TType = '{$this->TType}', web_type = '{$this->web_type}' where TID='{$this->TID}'";
		if ($db->query($sql)) {
			//更新模板文件

			$this->createAddDoc();
			if($type != 'all') { 
				//以下是修改模板文档表的修改时间
				if (!empty($this->DTName)) {
					$time = $_SERVER['REQUEST_TIME'];
					$sql = "UPDATE {$this->DTName} SET MendTime = '{$time}' ";
					$db->query($sql);
				}
			}
			return true;
		}
		return false;
	}
}
/*
CREATE TABLE `Template` (
  `TID` int(11) NOT NULL auto_increment,
  `TName` varchar(255) default NULL,
  `DTName` varchar(255) default NULL,
  `UID` int(11) default NULL,
  `Style` longtext,
  `Config` longtext,
  `UrlRule` varchar(255) default '/${TID}/${YYYY}/${MM}${DD}/${HH}${II}${SS}${D_ID}.html',
  `CreateTime` int(11) default NULL,
  PRIMARY KEY  (`TID`),
  UNIQUE KEY `DTName` (`DTName`),
  KEY `TName` (`TName`),
  KEY `CreateTime` (`CreateTime`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
*/
?>